package com.yuebook.smartrpc.framework.spring;

import com.yuebook.smartrpc.framework.provider.ProviderFactoryBean;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.beans.factory.config.RuntimeBeanReference;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.xml.AbstractSingleBeanDefinitionParser;
import org.w3c.dom.Element;

/**
 * @author honglei
 * @date 2018/11/19 下午4:06
 */
public class ProviderBeanDefinitionParser extends AbstractSingleBeanDefinitionParser {

    @Override
    protected Class<?> getBeanClass(Element element) {
        return ProviderFactoryBean.class;
    }

    @Override
    protected void doParse(Element element, BeanDefinitionBuilder builder) {
        try {
            String serviceItf = element.getAttribute("interface");
            String ref = element.getAttribute("ref");
            long timeout = Long.parseLong(element.getAttribute("timeout"));
            int port = Integer.parseInt(element.getAttribute("port"));
            String appKey = element.getAttribute("appKey");
            String groupName = element.getAttribute("groupName");
            String weight = element.getAttribute("weight");
            String workerThreads = element.getAttribute("workerThreads");
            builder.addPropertyValue("serviceItf", Class.forName(serviceItf));
            //获取引用对象
            RuntimeBeanReference reference = new RuntimeBeanReference(ref);
            builder.addPropertyValue("serviceObj", reference);
            builder.addPropertyValue("serverPort", port);
            builder.addPropertyValue("timeout", timeout);
            builder.addPropertyValue("appKey", appKey);
            if (StringUtils.isNotBlank(groupName)) {
                builder.addPropertyValue("groupName", groupName);
            }
            if (NumberUtils.isNumber(weight)) {
                builder.addPropertyValue("weight", Integer.parseInt(weight));
            }
            if (NumberUtils.isNumber(workerThreads)) {
                builder.addPropertyValue("workerThreads", Integer.parseInt(workerThreads));
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }
}
